/**
 * Description:
 *
 * @author      Eden
 * @datetime    2016/12/4 22:26
 * @copyright   Beijing CmsTop Technology Co.,Ltd.
 */

(function () {

    "use strict";

    var api = {
        saveThumbUrl: "/farm/base/upThumb?type=base&extra=slider",
        saveAddUrl: "/farm/base/doAdd",
        saveEditUrl: "/farm/base/doEdit",
        getStreamLists: '/stream/device/getAll',
        getDetail: '/farm/base/getDetail'
    };

    sm.controller('admin-base-index', ['$scope', '$http', 'Modal', function ($scope, $http, Modal) {

        var ue = UE.getEditor('container', {
            'autoClearinitialContent' : false,
            'toolbars' : [['fullscreen', 'source', 'preview', '|', 'bold', 'italic', 'underline', '|',
                'justifyleft', 'justifycenter', 'justifyright', '|', 'insertorderedlist', 'insertunorderedlist', 'blockquote', 'emotion',
                'link', 'removeformat', 'simpleupload', 'insertimage', '|', 'paragraph', 'fontsize',
                'inserttable']],
            'elementPathEnabled' : false,
            'initialFrameHeight': 250,
            'focus' : false,
            'maximumWords' : 999999,
            'zIndex': 999
        });

        $scope.pageType = pageType;
        $scope.thumbView = "";
        $scope.error = "";
        $scope.itemValue = {};
        $scope.editBaseId = 0;
        $scope.detail = {
            'baseId': 0,
            'baseName': "",
            'thumb': "",
            'telephone': "",
            'charger': "",
            'liveUrl': '',
            'phone': "",
            'address': "",
            'streamId': null,
            'content': ''
        };
        $scope.stream = {
            'streamId': 0,
            'deviceName': '----请选择----',
            'videoUrlHD': '',
            'videoUrlSD': ''
        };
        $scope.selectVideo = false;

        $scope.streamLists = [];
        (function () {
            $http.get(api.getStreamLists).success(function (res) {
                if (res.state) {
                    $scope.streamLists = res.data;
                }

                // 初始化
                $http.get(api.getDetail, {
                    params: {
                        baseId: baseId
                    }
                }).success(function (res) {
                    if (res.state) {
                        initValues(res.data);
                    }
                });

            });
        })();

        function initValues(detail) {
            if (!detail) {
                return false;
            }

            $scope.thumbView = detail.fullPath;
            $scope.editBaseId = detail.id;
            $scope.detail = {
                'baseId': detail.id,
                'baseName': detail.name,
                'thumb': detail.thumb,
                'liveUrl': detail.liveUrl,
                'telephone': detail.telephone,
                'charger': detail.charger,
                'phone': detail.phone,
                'address': detail.address,
                'streamId': detail.streamId,
                'content': detail.content
            };

            ue.ready(function () {
                ue.setContent(detail.content);
            });

            if (detail.streamId != 0) {
                angular.forEach($scope.streamLists, function (item) {
                    if (item['id'] == detail.streamId) {
                        $scope.stream = {
                            'streamId': detail.streamId,
                            'deviceName': item['deviceName'],
                            'videoUrlHD': item['videoUrlHD'],
                            'videoUrlSD': item['videoUrlSD']
                        };
                        $scope.selectVideo = false;
                    }
                });
            }

        }

        // 选择流
        $scope.selectStream = function ($index) {
            $scope.selectVideo = true;
            $scope.stream.deviceName = $scope.streamLists[$index]['deviceName'];
            $scope.stream.streamId = $scope.streamLists[$index]['id'];
            $scope.stream.videoUrlHD = $scope.streamLists[$index]['videoUrlHD'];
            $scope.stream.videoUrlSD = $scope.streamLists[$index]['videoUrlSD'];
        };
        $scope.viewVideo = function (url) {

            $('#videoModal').modal();
            var flashvars;
            flashvars={
                f: '/assets/library/ckplayer/m3u8.swf',
                a: url, //此处填写购买获取到的视频播放地址
                c: 0,
                p: 1,
                s: 4,
                lv: 1
            };
            var params = {bgcolor: '#FFF', allowFullScreen: true, allowScriptAccess: 'always', wmode: 'transparent'};
            CKobject.embedSWF("/assets/library/ckplayer/ckplayer.swf", "videoPlay", "video", "100%", "100%", flashvars, params);
        };


        var bak = angular.copy($scope.detail);

        // =============================================
        var $ = jQuery, uploader;

        // 初始化Web Uploader
        uploader = WebUploader.create({
            auto: true,
            server: api.saveThumbUrl,
            pick: '#uploadImage',
            duplicate: true,
            accept: {
                title: 'Images',
                extensions: 'gif,jpg,jpeg,png'
            }
        });

        uploader.on( 'uploadSuccess', function(file, res) {
            if (res.state) {
                $scope.detail.thumb = res.data.key;
                var b = res.data.url;
                $scope.thumbView = b || '';
                $scope.$apply();
            } else {
                var error = res.error ? res.error : '上传失败';
                Modal.error(error);
            }
        });

        // ===========end==================================

        // 保存数据
        $scope.saveBase = function () {

            if (!$scope.detail) {
                return false;
            }

            var html = ue.getContent();
            $scope.detail['content'] = html;

            if ($scope.selectVideo && $scope.stream.streamId) {
                $scope.detail['streamId'] = $scope.stream.streamId;
            }

            // 验证数据
            if (!checkParams()) {
                Modal.alert($scope.error);
                return false;
            }

            var url = $scope.pageType == 'edit' ? api.saveEditUrl : api.saveAddUrl;
            $http.post(url, $scope.detail).success(function (res) {
                if (res.state) {
                    Modal.success('修改成功');
                } else {
                    var error = res.error ? res.error : '修改失败';
                    Modal.error(error);
                }
            });

        };

        function checkParams() {

            var detail = $scope.detail;
            if (!detail.baseName) {
                $scope.error = "基地名称不能为空";
                return false;
            }

            if (!detail.charger) {
                $scope.error = "基地负责人姓名不能为空";
                return false;
            }

            if (detail.telephone && !/^0\d{2,3}-?\d{7,8}$/.test(detail.telephone)
                && !/^400-([0-9]){1}([0-9-]{7})$/.test(detail.telephone)) {
                $scope.error = "电话号码格式错误";
                return false;
            }

            if (!detail.phone) {
                $scope.error = "手机号不能为空";
                return false;
            }

            if (!detail.address) {
                $scope.error = "基地地址不能为空";
                return false;
            }

            if (!detail.thumb) {
                $scope.error = "请上传缩略图";
                return false;
            }

            if (detail.phone && !/^1[34578]\d{9}$/.test(detail.phone)) {
                $scope.error = "手机号格式错误";
                return false;
            }

            if ($scope.selectVideo && detail.streamId) {
                $scope.error = '视频流错误';
                return false;
            }

            if (!detail.content) {
                $scope.error = '基地介绍不能为空';
                return false;
            }

            return true;
        }


    }]);

})();